#include<cstdio>
#include<cstdlib>

#include "MedianFilter.h"

void qsort(unsigned char a[],int f,int l)//快速排序
{
    int i=f,j=l;
    unsigned char m=a[f];
    while(i<j)
    {
        while(i<j&&a[j]>=m)
            j--;
        if(i<j)
            a[i++]=a[j];
        while(i<j&&a[i]<m)
            i++;
        if(i<j)
            a[j--]=a[i];
    }
    a[i]=m;
    if(f<i-1)
        qsort(a,f,i-1);
    if(j+1<l)
        qsort(a,j+1,l);
}

unsigned char findmedian(unsigned char arr[], int num)//找到中位数
{
    qsort(arr, 0, num-1);
    if(num%2 == 0)
        return (arr[num/2]+arr[num/2-1])/2;
    else
        return arr[num/2];
}


MedianFilter::MedianFilter(int size) :Filter(size)
{;}

MedianFilter::~MedianFilter()
{;}

Image MedianFilter::Filtering(const Image &input)
{
    int h = input.Height();
    int w = input.Width();
    Image img(h, w);
    int size = filterSize;
    int num =0;
    unsigned char* arr = (unsigned char*)malloc(size*size);
    for(int rgb=0; rgb<3; ++rgb)        //RGB偏移
    {
        for(int i=0; i<h; ++i)
            for(int j=rgb; j<w*3; j+=3)
            {
                num = input.SquareArray(i, j, size, &arr);
                img.Set(i, j) = findmedian(arr, num);
            }
    }
    free(arr);
    return img;
}
